package com.lzq.course.system.controller.admin;

import com.alibaba.fastjson.JSON;
import com.lzq.course.server.dto.LoginUserDto;
import com.lzq.course.server.dto.UserDto;
import com.lzq.course.server.dto.PageDto;
import com.lzq.course.server.dto.ResponseDto;
import com.lzq.course.server.service.UserService;
import com.lzq.course.server.util.UuidUtil;
import com.lzq.course.server.util.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/user")
public class UserController {

    private final static Logger LOG = LoggerFactory.getLogger(UserController.class);

    public static final String BUSINESS_NAME = "用户";

    @Resource
    private UserService userService;

    @Resource
    RedisTemplate redisTemplate;

    /**
     * 查询列表 分页查询
     * @param pageDto
     * @return
     */
    @PostMapping("/list")
    public ResponseDto list(@RequestBody PageDto<UserDto> pageDto) {
        ResponseDto responseDto = new ResponseDto();
        userService.list(pageDto);

        responseDto.setContent(pageDto);
        return responseDto;
    }

    /**
     * 保存
     * @param userDto
     * @return
     */
    @PostMapping("/save")
    public ResponseDto save(@RequestBody UserDto userDto) {
        // 对密码进行二次加密
        userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));
        //保存校验
        ValidatorUtil.require(userDto.getLoginName(), "登陆名");
        ValidatorUtil.length(userDto.getLoginName(),"登陆名", 1, 50);
        ValidatorUtil.length(userDto.getName(),"昵称", 1, 50);
        ValidatorUtil.require(userDto.getPassword(), "密码");

        ResponseDto responseDto = new ResponseDto();
        userService.save(userDto);

        responseDto.setContent(userDto);
        return responseDto;
    }

    /**
     * 重置用户密码
     * @param userDto
     * @return
     */
    @PostMapping("/edit-password")
    public ResponseDto editPassword(@RequestBody UserDto userDto) {
        // 对密码进行二次加密
        userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));

        ResponseDto responseDto = new ResponseDto();
        userService.savePassword(userDto);

        responseDto.setContent(userDto);
        return responseDto;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResponseDto delete(@PathVariable String id) {
        ResponseDto responseDto = new ResponseDto();
        userService.delete(id);

        return responseDto;
    }

    /**
     * 用户【登录】
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    public ResponseDto login(@RequestBody UserDto userDto) {
        ResponseDto responseDto = new ResponseDto();

        LOG.info("用户登录开始");
        // 去缓存中session获取验证码是否正确 和用户输入的是否一致
        //String imageCode = (String) request.getSession().getAttribute(userDto.getImageCodeToken());
        // 【注意】
        // 这里永远会imageCode为空 每次调用sessionId 会不一样 【前后端分离项目会出现此问题】
        String imageCode = (String) redisTemplate.opsForValue().get(userDto.getImageCodeToken());
        LOG.info("从Redis中获取验证码：{}", imageCode);
        if (StringUtils.isEmpty(imageCode)) {
            responseDto.setSuccess(false);
            responseDto.setMessage("验证码过期");
            LOG.info("用户登录失败");
            return responseDto;
        }
        if (!imageCode.equalsIgnoreCase(userDto.getImageCode())) {
            responseDto.setSuccess(false);
            responseDto.setMessage("验证码错误");
            LOG.info("用户登录失败");
            return responseDto;
        } else {
            // 验证码通过 移除缓存
            LOG.info("验证码校验通过");
            //request.getSession().removeAttribute(userDto.getImageCodeToken());
            redisTemplate.delete(userDto.getImageCodeToken());
        }

        userDto.setPassword(DigestUtils.md5DigestAsHex(userDto.getPassword().getBytes()));

        LoginUserDto loginUserDto= userService.login(userDto);
        // 存储登录信息
//        HttpSession session = request.getSession();
//        session.setAttribute(Constants.LOGIN_USER, loginUserDto);
        String token = UuidUtil.getShortUuid();
        loginUserDto.setToken(token);
        redisTemplate.opsForValue().set(token, JSON.toJSONString(loginUserDto), 3600, TimeUnit.SECONDS); // 把用户存入redis

        responseDto.setContent(loginUserDto);

        return responseDto;
    }

    /**
     * 用户【退出登录】
     * @return
     */
    @GetMapping("/logout/{token}")
    public ResponseDto logout(HttpServletRequest request, @PathVariable String token) {
        ResponseDto responseDto = new ResponseDto();
        //request.removeAttribute(Constants.LOGIN_USER); // 清除登录信息
        LOG.info("退出登录删除token：{}", token);
        redisTemplate.delete(token);

        return responseDto;
    }
}
